package cn.schoolwow.util.module.query.resource.service;

import cn.schoolwow.quickflow.domain.FlowContext;
import cn.schoolwow.quickflow.flow.BusinessFlow;
import cn.schoolwow.util.module.query.resource.domain.ResourceQueryOption;

import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;

public class GetResourceAsURLFlow implements BusinessFlow {
    @Override
    public void executeBusinessFlow(FlowContext flowContext) throws Exception {
        getFromFile(flowContext);
        getFromClassLoader(flowContext);
        checkExist(flowContext);
    }

    @Override
    public String name() {
        return "获取资源文件并返回URL对象";
    }

    private void getFromFile(FlowContext flowContext) throws MalformedURLException {
        ResourceQueryOption resourceQueryOption = (ResourceQueryOption) flowContext.checkData("resourceQueryOption");

        File file = new File(resourceQueryOption.path);
        if(file.exists()){
            URL url = file.toURI().toURL();
            flowContext.putReturnData("file", file);
            flowContext.putTemporaryData("url", url);
            flowContext.brokenCurrentFlow("从文件中获取");
        }
    }

    private void getFromClassLoader(FlowContext flowContext){
        ResourceQueryOption resourceQueryOption = (ResourceQueryOption) flowContext.checkData("resourceQueryOption");

        ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
        URL url = classLoader.getResource(resourceQueryOption.path);
        if(null!=url){
            flowContext.putTemporaryData("url", url);
            flowContext.brokenCurrentFlow("从类加载器中获取");
        }
    }

    private void checkExist(FlowContext flowContext){
        URL url = (URL) flowContext.getData("url");
        ResourceQueryOption resourceQueryOption = (ResourceQueryOption) flowContext.checkData("resourceQueryOption");

        if(null==url){
            if(resourceQueryOption.checkExist){
                throw new IllegalArgumentException("["+resourceQueryOption.name+"]不存在!资源路径:"+resourceQueryOption.path);
            }
            flowContext.broken("资源文件不存在");
        }
    }
}
